<template>
  <el-dialog
    :title="isAdd ? '新增外部API' : '编辑外部API'"
    v-model="dialogVisible"
    width="800px"
    destroy-on-close
    @close="handleClose"
    :modal="true"
    :append-to-body="true"
    :lock-scroll="true"
    class="api-form-dialog"
  >
    <el-form
      ref="formRef"
      :model="localFormData"
      :rules="formRules"
      label-width="120px"
      :disabled="formLoading"
    >
      <!-- 基本信息 -->
      <el-divider content-position="left">
        <el-icon><InfoFilled /></el-icon>
        基本信息
      </el-divider>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="API名称" prop="function_name">
            <el-input
              v-model="localFormData.function_name"
              placeholder="请输入API名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="请求方法" prop="http_method">
            <el-select
              v-model="localFormData.http_method"
              placeholder="请选择请求方法"
              style="width: 100%"
            >
              <el-option label="GET" value="GET" />
              <el-option label="POST" value="POST" />
              <el-option label="PUT" value="PUT" />
              <el-option label="DELETE" value="DELETE" />
              <el-option label="PATCH" value="PATCH" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="接口地址" prop="endpoint_url">
        <el-input
          v-model="localFormData.endpoint_url"
          placeholder="请输入完整的API接口地址，如：https://api.example.com/data"
        />
      </el-form-item>
      
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="localFormData.description"
          type="textarea"
          :rows="2"
          placeholder="请输入API功能描述"
        />
      </el-form-item>

      <!-- 认证配置 -->
      <el-divider content-position="left">
        <el-icon><Lock /></el-icon>
        认证配置
      </el-divider>
      
      <el-form-item label="认证类型">
        <el-select
          v-model="authType"
          placeholder="请选择认证类型"
          style="width: 200px"
          @change="handleAuthTypeChange"
        >
          <el-option label="无认证" value="none" />
          <el-option label="API Key" value="api_key" />
          <el-option label="Bearer Token" value="bearer" />
          <el-option label="Basic Auth" value="basic" />
        </el-select>
      </el-form-item>
      
      <div v-if="authType === 'api_key'">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="API Key名称">
              <el-input
                v-model="apiKeyName"
                placeholder="如：X-API-Key"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="API Key值">
              <el-input
                v-model="apiKeyValue"
                type="password"
                show-password
                placeholder="请输入API Key"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      
      <div v-if="authType === 'bearer'">
        <el-form-item label="Bearer Token">
          <el-input
            v-model="bearerToken"
            type="password"
            show-password
            placeholder="请输入Bearer Token"
          />
        </el-form-item>
      </div>
      
      <div v-if="authType === 'basic'">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名">
              <el-input
                v-model="basicUsername"
                placeholder="请输入用户名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码">
              <el-input
                v-model="basicPassword"
                type="password"
                show-password
                placeholder="请输入密码"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 请求头配置 -->
      <el-divider content-position="left">
        <el-icon><Setting /></el-icon>
        请求头配置
      </el-divider>
      
      <el-form-item label="自定义请求头">
        <div class="headers-config">
          <div
            v-for="(header, index) in headersList"
            :key="index"
            class="header-item"
          >
            <el-input
              v-model="header.key"
              placeholder="请求头名称"
              style="width: 200px; margin-right: 10px"
            />
            <el-input
              v-model="header.value"
              placeholder="请求头值"
              style="width: 200px; margin-right: 10px"
            />
            <el-button
              type="danger"
              size="small"
              @click="removeHeader(index)"
            >
              删除
            </el-button>
          </div>
          <el-button
            type="primary"
            size="small"
            @click="addHeader"
          >
            <el-icon><Plus /></el-icon>
            添加请求头
          </el-button>
        </div>
      </el-form-item>

      <!-- 参数配置 -->
      <el-divider content-position="left">
        <el-icon><List /></el-icon>
        参数配置
      </el-divider>
      
      <el-form-item label="必需参数">
        <el-select
          v-model="localFormData.required_params"
          multiple
          filterable
          allow-create
          placeholder="请输入必需参数名称，按回车添加"
          style="width: 100%"
        >
        </el-select>
        <div class="form-tip">
          提示：输入参数名称后按回车键添加，这些参数在调用API时必须提供
        </div>
      </el-form-item>
      
      <el-form-item label="参数结构">
        <el-input
          v-model="parametersSchemaText"
          type="textarea"
          :rows="4"
          placeholder='请输入参数结构的JSON格式，例如：{"student_id": {"type": "string", "description": "学生ID"}}'
        />
        <div class="form-tip">
          提示：使用JSON格式定义参数结构，包括参数类型和描述
        </div>
      </el-form-item>

      <!-- 意图识别配置 -->
      <el-divider content-position="left">
        <el-icon><ChatDotRound /></el-icon>
        意图识别配置
      </el-divider>
      
      <el-form-item label="意图关键词">
        <el-select
          v-model="localFormData.intent_keywords"
          multiple
          filterable
          allow-create
          placeholder="请输入意图关键词，按回车添加"
          style="width: 100%"
        >
        </el-select>
        <div class="form-tip">
          提示：当用户输入包含这些关键词时，系统会识别为调用此API的意图
        </div>
      </el-form-item>
      
      <el-form-item label="示例语句">
        <el-select
          v-model="localFormData.intent_examples"
          multiple
          filterable
          allow-create
          placeholder="请输入示例语句，按回车添加"
          style="width: 100%"
        >
        </el-select>
        <div class="form-tip">
          提示：提供用户可能使用的示例语句，帮助系统更好地识别意图
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          :loading="formLoading"
          @click="handleSubmit"
        >
          {{ isAdd ? '创建' : '更新' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, computed } from 'vue'
import {
  InfoFilled,
  Lock,
  Setting,
  List,
  ChatDotRound,
  Plus,
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { createApiFunction, updateApiFunction, getApiFunctionDetail } from '@/api/external-api'

// 定义组件名
defineOptions({
  name: 'ApiForm',
})

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  formData: {
    type: Object,
    required: true,
  },
  isAdd: {
    type: Boolean,
    default: true,
  },
})

// Emits
const emit = defineEmits(['update:modelValue', 'success'])

// 状态
const formRef = ref(null)
const formLoading = ref(false)
const authType = ref('none')
const apiKeyName = ref('X-API-Key')
const apiKeyValue = ref('')
const bearerToken = ref('')
const basicUsername = ref('')
const basicPassword = ref('')
const headersList = ref([{ key: '', value: '' }])
const parametersSchemaText = ref('')

// 本地表单数据
const localFormData = reactive({
  function_name: '',
  description: '',
  endpoint_url: '',
  http_method: 'POST',
  headers: {},
  auth_config: {},
  parameters_schema: {},
  required_params: [],
  intent_keywords: [],
  intent_examples: [],
})

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value),
})

// 表单校验规则
const formRules = {
  function_name: [
    { required: true, message: '请输入API名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  endpoint_url: [
    { required: true, message: '请输入接口地址', trigger: 'blur' },
    {
      pattern: /^https?:\/\/.+/,
      message: '请输入有效的HTTP/HTTPS地址',
      trigger: 'blur',
    },
  ],
  http_method: [
    { required: true, message: '请选择请求方法', trigger: 'change' },
  ],
}

// 监听表单数据变化
watch(
  () => props.formData,
  (newData) => {
    if (newData) {
      Object.assign(localFormData, newData)
      
      // 解析认证配置
      if (newData.auth_config) {
        if (newData.auth_config.type === 'api_key') {
          authType.value = 'api_key'
          apiKeyName.value = newData.auth_config.key_name || 'X-API-Key'
          apiKeyValue.value = newData.auth_config.key_value || ''
        } else if (newData.auth_config.type === 'bearer') {
          authType.value = 'bearer'
          bearerToken.value = newData.auth_config.token || ''
        } else if (newData.auth_config.type === 'basic') {
          authType.value = 'basic'
          basicUsername.value = newData.auth_config.username || ''
          basicPassword.value = newData.auth_config.password || ''
        }
      }
      
      // 解析请求头
      if (newData.headers && Object.keys(newData.headers).length > 0) {
        headersList.value = Object.entries(newData.headers).map(([key, value]) => ({
          key,
          value,
        }))
      } else {
        headersList.value = [{ key: '', value: '' }]
      }
      
      // 解析参数结构
      if (newData.parameters_schema) {
        parametersSchemaText.value = JSON.stringify(newData.parameters_schema, null, 2)
      }
    }
  },
  { immediate: true, deep: true }
)

// 认证类型变化处理
const handleAuthTypeChange = () => {
  // 清空之前的认证配置
  apiKeyName.value = 'X-API-Key'
  apiKeyValue.value = ''
  bearerToken.value = ''
  basicUsername.value = ''
  basicPassword.value = ''
}

// 添加请求头
const addHeader = () => {
  headersList.value.push({ key: '', value: '' })
}

// 删除请求头
const removeHeader = (index) => {
  if (headersList.value.length > 1) {
    headersList.value.splice(index, 1)
  }
}

// 构建认证配置
const buildAuthConfig = () => {
  const authConfig = {}
  
  if (authType.value === 'api_key' && apiKeyName.value && apiKeyValue.value) {
    authConfig.type = 'api_key'
    authConfig.key_name = apiKeyName.value
    authConfig.key_value = apiKeyValue.value
  } else if (authType.value === 'bearer' && bearerToken.value) {
    authConfig.type = 'bearer'
    authConfig.token = bearerToken.value
  } else if (authType.value === 'basic' && basicUsername.value && basicPassword.value) {
    authConfig.type = 'basic'
    authConfig.username = basicUsername.value
    authConfig.password = basicPassword.value
  }
  
  return authConfig
}

// 构建请求头配置
const buildHeaders = () => {
  const headers = {}
  headersList.value.forEach((header) => {
    if (header.key && header.value) {
      headers[header.key] = header.value
    }
  })
  return headers
}

// 解析参数结构
const parseParametersSchema = () => {
  if (!parametersSchemaText.value.trim()) {
    return {}
  }
  
  try {
    return JSON.parse(parametersSchemaText.value)
  } catch (error) {
    ElMessage.error('参数结构JSON格式错误')
    return null
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    formLoading.value = true
    
    // 解析参数结构
    const parametersSchema = parseParametersSchema()
    if (parametersSchema === null) {
      formLoading.value = false
      return
    }
    
    // 构建提交数据
    const submitData = {
      ...localFormData,
      auth_config: buildAuthConfig(),
      headers: buildHeaders(),
      parameters_schema: parametersSchema,
    }
    
    // 调用实际的API接口
    if (props.isAdd) {
      await createApiFunction(submitData)
    } else {
      await updateApiFunction(props.formData.id, submitData)
    }
    
    ElMessage.success(props.isAdd ? '创建成功' : '更新成功')
    emit('success')
    handleClose()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败: ' + (error.message || '未知错误'))
  } finally {
    formLoading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}
</script>

<style scoped>
.api-form-dialog {
  z-index: 9999;
}

.api-form-dialog :deep(.el-dialog) {
  margin: 5vh auto;
  max-height: 90vh;
  overflow-y: auto;
}

.api-form-dialog :deep(.el-overlay) {
  background-color: rgba(0, 0, 0, 0.5);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9998;
}

.api-form-dialog :deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
  padding: 20px;
}

.headers-config {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  background-color: #fafafa;
}

.header-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.header-item:last-of-type {
  margin-bottom: 15px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.4;
}

:deep(.el-divider__text) {
  font-weight: 600;
  color: #409eff;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

.dialog-footer {
  text-align: right;
}
</style>